import hashlib
import json
import random
from time import time

import jsonpath
import requests

url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36",
    "Referer" : "https://fanyi.youdao.com/",
    "Cookie":"OUTFOX_SEARCH_USER_ID=-911498467@10.110.96.160; JSESSIONID=aaajj0ZOfdqXV4eHdCS9x; OUTFOX_SEARCH_USER_ID_NCOO=844024576.9357864; fanyi-ad-id=305002; fanyi-ad-closed=1; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abcwTpAETJKLn8YTuzU9x; _ntes_nnid=b3474f1e2e16b752dbe3664508f17922,1646824607836; ___rl__test__cookies=1647059827790"
}
# 设置死循环，可以不断进行翻译请求
while True:
    word = input("请输入您要翻译的内容：")
    # 模拟有道翻译data_form数据生成机制
    # 1、生成时间戳
    lts = str(int(time()*1000))
    # print(r)
    # 2、时间戳与随机数字的符串形式拼接
    salt = lts + str(random.randint(0,9))
    # print(i)
    # 键sign的值的生成
    sign = hashlib.md5(("fanyideskweb"+word+salt+"Ygy_4c=r#e#4EX^NUGUc5").encode()).hexdigest()
    data_form = {""
        "i": word,
        "from": "AUTO",
        "to": "AUTO",
        "smartresult": "dict",
        "client": "fanyideskweb",
        "salt": salt,    #salt的植入
        "sign": sign,    #sign的植入
        "lts": lts,      #lts的植入
        "bv": "e486e2b600e579ce59630b9cf4555736",
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "action": "FY_BY_CLICKBUTTION"
    }
    #捕获异常
    try:
        # 发送请求
        res = requests.post(url,headers = headers,data = data_form)

    # 接受json数据并转换为python数据
        py_data = res.json()
        # print(py_data)
        # word_ = jsonpath.jsonpath(py_data,"$..src")[0]
        str_ = jsonpath.jsonpath(py_data,"$..tgt")[0]
        print("翻译的结果是：",str_)
    except:
        print("抱歉，我还在学习该语种中")